<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <label class="el-form-item-label">周</label>
      <span>
        <el-date-picker
          v-model="query.beginDate"
          class="filter-item"
          type="week"
          format="yyyy 第 WW 周"
          placeholder="选择周"
          @change="changeDate"
        />
      </span>
      <!-- <el-button class="filter-item" size="mini" type="success" icon="el-icon-search" @click="doList">搜索</el-button>  -->
      <el-button type="defalut" icon="el-icon-download" :loading="downloadLoading" style="float: right;" @click="doExport">导出</el-button>
      <!-- <el-button class="filter-item" size="mini" type="warning" @click="goview">预览</el-button> -->
    </div>
    <!--表格渲染-->
    <div
      data-v-eba2317e=""
      class="el-table el-table--fit el-table--border el-table--group el-table--enable-row-hover el-table--enable-row-transition el-table--small"
      style="width: 100%"
    >
      <div class="el-table__header-wrapper">
        <table
          cellspacing="0"
          cellpadding="0"
          border="0"
          class="el-table__header"
          width="100%"
        >
          <colgroup>
            <col name="el-table_14_column_109">
            <col name="el-table_14_column_110" width="198">
            <col name="el-table_14_column_111_column_112_column_113" width="198">
            <!-- <col name="el-table_14_column_110"  width="198"/> -->
          </colgroup>
          <thead class="is-group has-gutter">
            <tr class="">
              <th class="el-table_14_column_109 is-leaf el-table__cell"> <div class="cell">责任单位</div> </th>
              <th class="el-table_14_column_110 is-leaf el-table__cell"> <div class="cell">未整改问题数</div> </th>
              <th class="el-table_14_column_110 is-leaf el-table__cell"> <div class="cell">点位数</div> </th>
              <!-- <th class="el-table_14_column_110 is-leaf el-table__cell" > <div class="cell">操作</div> </th>  -->
            </tr>
          </thead>
        </table>
      </div>
      <div class="el-table__body-wrapper is-scrolling-none">
        <table
          cellspacing="0"
          cellpadding="0"
          border="0"
          class="el-table__body"
          width="100%"
        >
          <colgroup>
            <col name="el-table_14_column_109">
            <col name="el-table_14_column_110" width="198">
            <col name="el-table_14_column_111_column_112_column_113" width="198">
            <!-- <col name="el-table_14_column_110"  width="198"/> -->
          </colgroup>
          <tbody>
            <tr v-for="(item,index) in crud.data" :key="index" class="el-table__row">

              <td
                colspan="1"
                class="el-table_14_column_109 el-table__cell"
              >
                <div class="cell "><div>{{ item.name }}</div></div>
              </td>
              <td
                rowspan="1"
                colspan="1"
                class="el-table_14_column_110 el-table__cell"
              >
                <div class="cell ">{{ item.num }}</div>
              </td>
              <td
                rowspan="1"
                colspan="1"
                class="el-table_14_column_111_column_112_column_114 el-table__cell"
              >
                <div class="cell ">{{ item.pnum }}</div>
              </td>
              <!-- <td
                rowspan="1"
                colspan="1"
                class="el-table_14_column_111_column_112_column_114 el-table__cell"
              >
                <div class="cell " >
                  <el-button
                    class="filter-item"
                    size="mini"
                    type="warning"
                    @click="goview"
                  >预览</el-button></div>
              </td>   -->
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import crudweeklyReports from '@/api/system/weeklyReports'
import { downloadFile } from '@/utils/index'
import CRUD, { presenter, header, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import { parseTime } from '@/utils/index'
import { ExportBriefDataDocx } from '@/utils/exportWordImage'
export default {
  name: 'GeneratorIndex',
  components: { crudOperation, rrOperation },
  mixins: [presenter(), header(), crud()],
  cruds() {
    const allvaue = new Date()
    const beginDate = parseTime(+new Date(allvaue.getFullYear(), allvaue.getMonth(), allvaue.getDate() - allvaue.getDay()), '{y}-{m}-{d}')
    const endDate = parseTime(+new Date(allvaue.getFullYear(), allvaue.getMonth(), allvaue.getDate() + (6 - allvaue.getDay())), '{y}-{m}-{d}')
    return CRUD({
      title: '督察通报',
      url: '/api/tEvent/superviseReport',
      query: { beginDate: beginDate, endDate: endDate },
      page: {}
    })
  },
  data() {
    return {
      syncLoading: false,
      list: [],
      downloadLoading: false,
      itemData: [],
      host: process.env.VUE_APP_BASE_API
    }
  },
  created() {
    this.crud.optShow = {
      add: false,
      edit: false,
      del: false,
      download: false
    }
    // this.doList()
    this.doInit()
  },
  methods: {
    parseTime,
    changeDate(val) {
      const allvaue = val
      this.query.beginDate = parseTime(+new Date(allvaue.getFullYear(), allvaue.getMonth(), allvaue.getDate() - allvaue.getDay()), '{y}-{m}-{d}')
      this.query.endDate = parseTime(+new Date(allvaue.getFullYear(), allvaue.getMonth(), allvaue.getDate() + (6 - allvaue.getDay())), '{y}-{m}-{d}')
      // this.doList()
      this.crud.refresh()
      this.doInit()
    },
    // doList(){
    //   crudUnitInspectorateSituation.list(this.query).then((res)=>{
    //     this.list =res
    //   })
    // },
    doExport() {
      const date = document.querySelectorAll('.filter-item .el-input__inner')[0].value
      const pdate = `${new Date().getFullYear()} 年 第  ${date.split(' ')[2]} 期`
      // 设置模板变量的值
      const data = {
        pdate: pdate,
        currDate: parseTime(new Date(), '{y} 年 {m} 月 {d} 日 '),
        tableData: this.list,
        itemlist: this.itemData
      }
      const imgSize = {
        imgurl: [315, 215]// 控制导出的word图片大小
      }
      ExportBriefDataDocx(`${'/ducha'}.docx`, data, '督查通报.docx', imgSize)
    },
    async  goview() {
      await this.doInit()
      const date = document.querySelectorAll('.filter-item .el-input__inner')[0].value
      const pdate = `"${new Date().getFullYear()} 年 第  ${date.split(' ')[2]} 期"`

      setTimeout(() => {
      // this.$router.push({ path: '/system/weeklyReports/view', query: { dateString: date, beginDate: this.query.beginDate, endDate: this.query.endDate }})
        window.open('/test.html?dateString=' + pdate + '&currDate=' + JSON.stringify(parseTime(new Date(), '{y}-{m}-{d}')) + '&itemData=' + JSON.stringify(this.itemData) + '&list=' + JSON.stringify(this.list))
      }, 800)
    },

    doInit() {
      

      const loading = this.$loading({
        lock: true,
        text: "数据加载中",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      crudweeklyReports.selectUntreatedEventByDate({ ...this.query }).then((res) => {
        this.itemData = []
        this.itemData = res.map((i, ix) => { i.index = ix + 1; i.attachments.map(async o => { o.url = await this.getBase64Sync(this.host + o.url); return o }); return i })
        console.log(this.itemData)
         loading.close();
      })
      crudweeklyReports.list({ ...this.query }).then((res) => {
        this.list = []
        this.list = res.content
      })
    },
    getBase64Sync(imgUrl) {
      return new Promise(function(resolve, reject) {
        // 一定要设置为let，不然图片不显示
        const image = new Image()
        // 图片地址
        image.src = imgUrl
        // 解决跨域问题
        image.setAttribute('crossOrigin', '*') // 支持跨域图片
        // image.onload为异步加载
        image.onload = function() {
          const canvas = document.createElement('canvas')
          canvas.width = image.width
          canvas.height = image.height
          const context = canvas.getContext('2d')
          context.drawImage(image, 0, 0, image.width, image.height)
          // 图片后缀名
          const ext = image.src.substring(image.src.lastIndexOf('.') + 1).toLowerCase()
          // 图片质量
          const quality = 0.8
          // 转成base64
          const dataurl = canvas.toDataURL('image/' + ext, quality)
          // 返回
          resolve(dataurl)
        }
      })
    },
    base64DataURLToArrayBuffer(dataURL) {
      debugger
      const base64Regex = /^data:image\/(png|jpg|jpeg|svg|svg\+xml);base64,/
      if (!base64Regex.test(dataURL)) {
        return false
      }
      const stringBase64 = dataURL.replace(base64Regex, '')
      let binaryString
      if (typeof window !== 'undefined') {
        binaryString = window.atob(stringBase64)
      } else {
        binaryString = new Buffer(stringBase64, 'base64').toString('binary')
      }
      const len = binaryString.length
      const bytes = new Uint8Array(len)
      for (let i = 0; i < len; i++) {
        const ascii = binaryString.charCodeAt(i)
        bytes[i] = ascii
      }
      return bytes.buffer
    }
  }
}
</script>

<style scoped>
</style>
